package com.ruoyi.business.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.business.domain.TChat;
import com.ruoyi.business.domain.vo.TChatVo;
import com.ruoyi.business.service.IChatService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.management.Query;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/business/chat")
public class ChatController extends BaseController {

    @Autowired
    private IChatService chatService;

    @Autowired
    private ISysUserService userService;

    @GetMapping("/records")
    public AjaxResult getChatRecords() {
        String userId = getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        QueryWrapper<TChat> wrapper = new QueryWrapper<>();
        wrapper.eq("class_id", sysUser.getMyClass())
                .orderByAsc("create_time");
        List<TChat> list = chatService.list(wrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<TChatVo> collect = list.stream().map(item -> {
            TChatVo vo = new TChatVo();
            BeanUtils.copyProperties(item, vo);
            SysUser sysUser1 = userService.selectUserById(String.valueOf(vo.getUserId()));
            vo.setUser(sysUser1);
            vo.setCreateTime(sdf.format(new Date(item.getCreateTime())));
            if (userId.equals(String.valueOf(vo.getUserId()))) {
                vo.setIsOwn(true);
            } else {
                vo.setIsOwn(false);
            }
            return vo;
        }).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

}
